// 应急措施
import React, { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { 
  Plus, Search, Shield, Edit, Trash2, MoreHorizontal,
  ChevronLeft, ChevronRight
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";

import EmergencyMeasureTemplateForm from "./EmergencyMeasureTemplateForm";

export default function EmergencyMeasureTemplateManager({
  templates,
  onSave,
  onDelete,
  isLoading,
  onFilteredCountChange,
}) {
  const [showForm, setShowForm] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterCategory, setFilterCategory] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10); // 每页显示条数

  // 编辑操作
  const handleEdit = (template) => {
    setEditingTemplate(template);
    setShowForm(true);
    setTimeout(() => {
      const formElement = document.getElementById("emergency-measure-form");
      if (formElement) {
        formElement.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    }, 250);
  };

  // 取消表单
  const handleCancel = () => {
    setEditingTemplate(null);
    setShowForm(false);
  };

  // 提交表单
  const handleSubmit = async (data) => {
    await onSave(editingTemplate ? { ...data, id: editingTemplate.id } : data);
    handleCancel();
  };

  // 过滤模板
  const filteredTemplates = useMemo(() => {
    return templates.filter((template) => {
      const termMatch =
        searchTerm === "" ||
        (template.incidentType &&
          template.incidentType
            .toLowerCase()
            .includes(searchTerm.toLowerCase())) ||
        (template.description &&
          template.description
            .toLowerCase()
            .includes(searchTerm.toLowerCase())) ||
        (template.code &&
          template.code.toLowerCase().includes(searchTerm.toLowerCase()));
      const categoryMatch =
        filterCategory === "all" || template.category === filterCategory;
      return termMatch && categoryMatch;
    });
  }, [templates, searchTerm, filterCategory]);

  // 分页数据计算
  const totalItems = filteredTemplates.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const paginatedTemplates = filteredTemplates.slice(indexOfFirstItem, indexOfLastItem);

  // 分页处理函数
  const handlePageChange = (pageNum) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
      // 分页切换时滚动到表格顶部
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 切换每页条数重置页码
  };

  // 当筛选结果变化时重置页码并通知数量变化
  useEffect(() => {
    setCurrentPage(1);
    if (onFilteredCountChange) {
      onFilteredCountChange(filteredTemplates.length);
    }
  }, [filteredTemplates.length, onFilteredCountChange]);

  // 渲染分页组件（使用你提供的样式）
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  // 类别相关配置
  const categories = [
    ...new Set(templates.map((t) => t.category).filter(Boolean)),
  ];
  
  const categoryLabels = {
    personnelInjury: "人员伤害",
    equipmentFailure: "设备故障",
    fireAccident: "火灾事故",
    electricShock: "触电事故",
    fallFromHeight: "高处坠落",
    environmentalIncident: "环境事件",
    trafficAccident: "交通事故",
    other: "其他",
  };

  const categoryColors = {
    personnelInjury: "bg-red-100 text-red-700",
    equipmentFailure: "bg-yellow-100 text-yellow-700",
    fireAccident: "bg-orange-100 text-orange-700",
    electricShock: "bg-amber-100 text-amber-700",
    fallFromHeight: "bg-purple-100 text-purple-700",
    environmentalIncident: "bg-green-100 text-green-700",
    trafficAccident: "bg-indigo-100 text-indigo-700",
    other: "bg-gray-100 text-gray-700"
  };

  return (
    <div className="space-y-6">
      {/* 搜索和筛选区域 */}
      <div className="flex flex-col md:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            placeholder="搜索事故类型、描述或编码..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={filterCategory} onValueChange={setFilterCategory}>
          <SelectTrigger className="w-full md:w-[180px]">
            <SelectValue placeholder="所有类别" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">所有类别</SelectItem>
            {categories.map((cat) => (
              <SelectItem key={cat} value={cat}>
                {categoryLabels[cat] || cat}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Button
          onClick={() => {
            setEditingTemplate(null);
            setShowForm(true);
          }}
          className="bg-blue-600 hover:bg-blue-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          新建应急措施
        </Button>
      </div>

      {/* 表单区域 */}
      {showForm && (
        <EmergencyMeasureTemplateForm
          template={editingTemplate}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
          id="emergency-measure-form"
        />
      )}

      {/* 表格内容区域 */}
      {isLoading ? (
        <div className="text-center p-8">加载中...</div>
      ) : totalItems > 0 ? (
        <div className="rounded-lg border border-gray-200 overflow-hidden shadow-sm">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-gray-50 border-b border-gray-200">
                <TableRow>
                  <TableHead className="w-[150px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    事故类型
                  </TableHead>
                  <TableHead className="min-w-[200px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    描述
                  </TableHead>
                  <TableHead className="w-[120px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    类别
                  </TableHead>
                  <TableHead className="w-[150px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    处置负责人
                  </TableHead>
                  <TableHead className="min-w-[180px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    应急设备
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-right text-sm font-semibold text-gray-700">
                    操作
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {paginatedTemplates.map((template) => (
                  <TableRow
                    key={template.id}
                    className="transition-colors duration-150 border-b border-gray-100 last:border-0 hover:bg-gray-50"
                  >
                    <TableCell className="py-3 px-4 text-gray-800 text-sm">
                      {template.incidentType || <span className="text-gray-400">未命名事件</span>}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm">
                      {template.description 
                        ? (template.description.length > 30 
                          ? `${template.description.slice(0, 30)}...` 
                          : template.description)
                        : <span className="text-gray-400">-</span>
                      }
                    </TableCell>
                    <TableCell className="py-3 px-4">
                      <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${categoryColors[template.category] || categoryColors.other}`}>
                        {categoryLabels[template.category] || template.category}
                      </span>
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm">
                      {template.responsiblePersonRole || <span className="text-gray-400">未指定</span>}
                    </TableCell>
                    <TableCell className="py-3 px-4 text-gray-700 text-sm">
                      {template.requiredEquipment 
                        ? (template.requiredEquipment.length > 20 
                          ? `${template.requiredEquipment.slice(0, 20)}...` 
                          : template.requiredEquipment)
                        : <span className="text-gray-400">无</span>
                      }
                    </TableCell>
                    <TableCell className="py-3 px-4 text-right">
                      {/* 操作下拉菜单 */}
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-gray-600 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                          >
                            <MoreHorizontal className="w-4 h-4" />
                            <span className="sr-only">打开操作菜单</span>
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-[140px] border-gray-200">
                          <DropdownMenuItem
                            onClick={() => handleEdit(template)}
                            className="cursor-pointer hover:bg-blue-50 hover:text-blue-700"
                          >
                            <Edit className="w-4 h-4 mr-2" />
                            编辑
                          </DropdownMenuItem>
                          <DropdownMenuSeparator className="bg-gray-100" />
                          <DropdownMenuItem
                            onClick={() => onDelete(template.id)}
                            className="text-red-600 cursor-pointer hover:bg-red-50"
                          >
                            <Trash2 className="w-4 h-4 mr-2" />
                            删除
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {/* 分页组件 */}
          {renderPagination()}
        </div>
      ) : (
        <div className="text-center py-12 text-gray-500 bg-white rounded-lg shadow-sm border border-gray-200">
          <Shield className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p className="text-lg font-medium mb-2">暂无匹配的应急措施模板</p>
          <p>尝试调整搜索条件或创建新的模板</p>
        </div>
      )}
    </div>
  );
}